function * myGenerator () {
  yield 1
  yield 2
  yield 3
  yield 5
  yield 8
  yield 13
}
// 调用生成器函数获得一个迭代器对象
const iterator = myGenerator()
// for (const number of iterator) {
//   console.log(number)
// }

function asyncTask (num) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(num * 3)
    }, 1000)
  })
}

function syncTask (num) {
  return num * 3
}

function * generator(initNum) {
  const v1 = yield asyncTask(initNum)
  const v2 = yield syncTask(v1)
  const v3 = yield asyncTask(v2)
  return v3
}

function asyncToGenerator (generatorFn) {
  return function () {
    return new Promise(((resolve, reject) => {
      // 调用生成器函数获取对应的迭代器对象
      const iterator = generatorFn.apply(this, arguments)
      function next (key = 'next', arg) {
        let result
        try {
          // 默认调用迭代器的next方法，拿到迭代结果对象
          result = iterator[key](arg)
        } catch (error) {
          reject(error)
        }
        // value按异步任务来处理，它是一个Promise对象
        const { value, done } = result
        if (done) { // 如果迭代结束则返回value
          resolve(value)
        } else {
          // 没有迭代结束的情况下，等当前任务执行完毕再开始下一个任务
          // 因为value可能是同步任务，所以需要用Promise.resolve包装
          Promise.resolve(value).then(
            res => {
              console.log(res, 'res')
              next('next', res)
            },
            err => {
              next('error', err)
            }
          )
        }
      }
      next('next')
    }))
  }
}

const asyncFn = asyncToGenerator(generator)
asyncFn(3).then(res => {
  console.log(res)
})
